package com.xy.websocket.ws;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 谢阳
 * @version 1.0
 * @date 2024-07-11 14:41
 * @description
 */
@ServerEndpoint("/simple/{name}")
@Slf4j
@Component
@EnableScheduling
@SuppressWarnings("unused")
public class SimpleEndpoint {

    private static final Map<String, Session> sessions = new HashMap<>();

    private final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @OnOpen
    public void onOpen(Session session,@PathParam("name") String name) {
        sessions.put(name, session);
        log.info("注册用户 [{}],同时在线数 [{}]",name,sessions.size());
    }

    @OnMessage
    public void onMessage(String message, Session session,@PathParam("name") String name) {
        String[] split = message.split(":");
        if (split.length == 2) {
            Session sendSession = sessions.get(split[0]);
            if (sendSession != null) {
                LocalDateTime now = LocalDateTime.now();
                String format = DTF.format(now);
                sendSession.getAsyncRemote().sendText(format + " " + name + ":" + split[1]);
            } else {
                session.getAsyncRemote().sendText("用户未上线");
            }
        } else{
            session.getAsyncRemote().sendText("服务端收到消息");
        }
    }

    @OnClose
    public void onClose(Session session, @PathParam("name") String name)  throws IOException {
        int oldSize = sessions.size();
        Session remove = sessions.remove(name);
        log.info("在线数 [{}],退出用户 [{}],剩余在线 [{}] 个",oldSize,name,sessions.size());
        remove.close();
    }

    @Scheduled(cron = "*/20 * * * * ?")
    public void task() {
        LocalDateTime now = LocalDateTime.now();
        String format = DTF.format(now);
        sessions.forEach((k, v) -> {
            String string = Arrays.stream(sessions.keySet().toArray()).collect(Collectors.toList()).toString();
            v.getAsyncRemote().sendText(format + " 同时在线数 [" + sessions.size()+ "] 个" + ", 在线用户 " + string);
        });
    }
}
